import {
  getSetting,
  chooseAddress,
  openSetting,
  showModal,
  showToast
} from "../../utils/asyncWX.js"
import regeneratorRuntime, {
  async
} from "../../lib/runtime/runtime.js"

//调用小程序内置的api 获取用户的收货地址
Page({
  data: {
    address: {},
    carts: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },
  onShow: function () {
    let carts = wx.getStorageSync("cart") || [];
    //如果carts是空数组，调用every,返回值就是true
    // let allChecked=carts.length?carts.every(e=>e.checked):false;
    this.setCart(carts);
    this.setData({
      address: wx.getStorageSync("address")
    })
  },
  //点击收货地址
  async handleChooseAddress() {
    //获取用户对小程序所授予获取地址的权限状态scope
    //假设用户授予获取地址的权限为true  则scope为true
    //获取用户权限的代码(scope.address: true)
    // wx.getSetting({
    //   success(res) {
    //     const scopedAddress = res.authSetting["scope.address"];
    //     if (scopedAddress === true || scopedAddress === undefined) {
    //       wx.chooseAddress({
    //         success: (result) => {
    //           console.log(result);
    //         }
    //       });
    //     }else {
    //       //用户以前拒绝过授予权限，先诱导用户打开授权页面
    //       wx.openSetting({
    //         success: (result) => {
    //           wx.chooseAddress({
    //             success: (result) => {
    //               console.log(result);
    //             }
    //           });
    //         }
    //       });
    //     }
    //   }
    // })
    try {
      const res1 = await getSetting();
      const scopedAddress = res1.authSetting["scope.address"];
      if (scopedAddress === false) {
        await openSetting();
      }
      let address = await chooseAddress();
      address.all = address.provinceName + address.cityName + address.countyName;
      wx.setStorageSync("address", address);
    } catch (error) {
      console.log(error);
    }
  },
  handleItemChange(e) {
    //获取被修改的商品id
    const goods_id = e.currentTarget.dataset.id;
    //获取购物车数组
    let {
      carts
    } = this.data;
    //找到被修改的商品对象
    let index = carts.findIndex(ele => ele.goods_id === goods_id);
    //选中状态取反
    carts[index].checked = !carts[index].checked;
    //把购物车数据重新设置回data中和缓存中
    wx.setStorageSync("cart", carts);
    //重新计算 底部工具栏的数据 全选 总价格 购买的数量函数的封装
    this.setCart(carts);
  },
  // 重新计算 底部工具栏的数据 全选 总价格 购买的数量函数的封装
  setCart(carts) {
    let totalPrice = 0;
    let totalNum = 0;
    let allChecked = true;
    carts.forEach(ele => {
      if (ele.checked) {
        totalPrice += ele.num * ele.goods_price;
        totalNum += ele.num;
      } else {
        allChecked = false;
      }
    });
    //判断数组是否为空
    allChecked = carts.length != 0 ? allChecked : false;
    this.setData({
      carts,
      allChecked,
      totalPrice,
      totalNum
    })
    wx.setStorageSync("cart", carts)
  },
  //商品的全选功能
  handleItemAllCheck() {
    //1.获取data中的数据
    let {
      carts,
      allChecked
    } = this.data;
    //allchecked取反
    allChecked = !allChecked;
    //遍历购物车中的数据，让里面的商品选中状态跟随allChecked改变而改变
    carts.forEach(ele => ele.checked = allChecked);
    //把修改后的值重新填充回data和缓存中
    this.setData({
      carts
    })
    this.setCart(carts);
  },
  //商品数量的操作
 async handleItemNumEdit(e) {
    //获取传递过来的参数
    const {
      operation,
      id
    } = e.currentTarget.dataset;
    //获取购物车数组
    let {
      carts
    } = this.data;
    //找到需要修改的商品的索引
    const index = carts.findIndex(ele => ele.goods_id === id);
    if (carts[index].num === 1 && operation === -1) {
      const res=await showModal({content:"请问您是否要删除呢"})
      if (res.confirm) {
        carts.splice(index, 1);
        this.setCart(carts);
      }
    } else {
      //进行数量修改
      carts[index].num += operation;
      //重新计算 底部工具栏的数据 全选 总价格 购买的数量函数的封装
      this.setCart(carts);
    }
  },
  //点击结算支付
  async handlePay(){
    //1.判断收货地址
    const {address,totalNum}=this.data;
    if(!address.userName){
      await showToast({title:"您还没有选择收货地址"})
      return;
    }
    //2.判断用户有没有选择商品（totalNum不为0）
    if(totalNum===0){
      await showToast({title:"您还没有选购商品"})
      return;
    }
    //跳转到支付页面
    wx.navigateTo({
      url: '/pages/pay/index'
    });
      
  }
})